﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;

namespace gaeproxy
{
    public partial class gaeproxyForm : Form
    {
        Process gae = null;
        Thread gaeThread = null;
        //string status = "stopped";
        string mode = "1";
        string keyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
        string exePath = @"D:\Program Files\wallproxy-plus\local\proxy.exe";
        public gaeproxyForm()
        {
            InitializeComponent();
        }

        private void gaeproxyForm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.notifyIcon.Visible = true;
                this.Hide();
            }
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.Hide();
                this.WindowState = FormWindowState.Minimized;
            } 
            else
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void gaeproxyForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = this.Visible;
            this.WindowState = FormWindowState.Minimized;
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            using (RegistryKey runKey = Registry.CurrentUser.OpenSubKey(keyPath, true))
            {
                runKey.DeleteValue("AutoConfigURL", false);
                runKey.DeleteValue("ProxyServer", false);
                runKey.Close();
            }
            try
            {
                gae.Kill();
            }
            catch { }
            this.Hide();
            Application.Exit();
        }

        //private void StartStopProxy(string status)
        //{
        //    string mode = this.mode;
        //    startMenuItem.Checked = false;
        //    stopMenuItem.Checked = false;
        //    using (RegistryKey runKey = Registry.CurrentUser.OpenSubKey(keyPath, true))
        //    {
        //        switch (status)
        //        {
        //            case "start":
        //            case "running":
        //                startMenuItem.Checked = true;
        //                SetIEProxy(this.mode);
        //                if (gaeThread == null || gaeThread.ThreadState == System.Threading.ThreadState.Stopped)
        //                {
        //                    gaeThread = new Thread(running);
        //                    gaeThread.Start();
        //                }
        //                else
        //                {
        //                    StartStopProxy("stopped");
        //                }
        //                break;
        //            default:
        //                try
        //                {
        //                    gae.Kill();
        //                }
        //                catch { }
        //                mode = "0";
        //                dirctMenuItem.Checked = true;
        //                pacMenuItem.Checked = false;
        //                agentMenuItem.Checked = false;
        //                stopMenuItem.Checked = true;
        //                runKey.DeleteValue("AutoConfigURL", false);
        //                runKey.DeleteValue("ProxyServer", false);
        //                status = "stopped";
        //                break;
        //        }
        //        runKey.SetValue("ProxyStatus", status);
        //        runKey.Close();
        //    }
        //    this.status = status;
        //    this.notifyIcon.Icon = (Icon)Properties.Resources.ResourceManager.GetObject(status + mode);
        //}

        private void SetIEProxy(string mode)
        {
            dirctMenuItem.Checked = false;
            pacMenuItem.Checked = false;
            agentMenuItem.Checked = false;
            using (RegistryKey runKey = Registry.CurrentUser.OpenSubKey(keyPath, true))
            {
                runKey.DeleteValue("AutoConfigURL", false);
                runKey.DeleteValue("ProxyServer", false);
                runKey.SetValue("ProxyEnable", 0);
                switch (mode)
                {
                    case "1":
                        if (gaeThread == null || gaeThread.ThreadState == System.Threading.ThreadState.Stopped)
                        {
                            gaeThread = new Thread(running);
                            gaeThread.Start();
                        }
                        pacMenuItem.Checked = true;
                        runKey.SetValue("AutoConfigURL", @"file://" + exePath.Replace("proxy.exe", "proxy.pac"));
                        break;
                    case "2":
                        if (gaeThread == null || gaeThread.ThreadState == System.Threading.ThreadState.Stopped)
                        {
                            gaeThread = new Thread(running);
                            gaeThread.Start();
                        }
                        agentMenuItem.Checked = true;
                        runKey.SetValue("ProxyEnable", 1);
                        runKey.SetValue("ProxyServer", "127.0.0.1:8086");
                        break;
                    default:
                        try
                        {
                            gae.Kill();
                        }
                        catch { }
                        mode = "0";
                        runKey.DeleteValue("AutoConfigURL", false);
                        runKey.DeleteValue("ProxyServer", false);
                        dirctMenuItem.Checked = true;
                        break;
                }
                runKey.SetValue("ProxyMode", mode);
                runKey.Close();
            }
            this.mode = mode;
            this.notifyIcon.Icon = (Icon)Properties.Resources.ResourceManager.GetObject("running" + mode);
        }

        private static void SetAutoRun(string keyName, string filePath)
        {
            using (RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\Currentversion\Run", true))
            {
                runKey.SetValue(keyName, filePath);
                runKey.Close();
            }
        }

        private void dirctMenuItem_Click(object sender, EventArgs e)
        {
            SetIEProxy("0");
        }

        private void pacMenuItem_Click(object sender, EventArgs e)
        {
            SetIEProxy("1");
        }

        private void agentMenuItem_Click(object sender, EventArgs e)
        {
            SetIEProxy("2");
        }

        private void gaeproxyForm_Load(object sender, EventArgs e)
        {
            this.Hide();
            if (!File.Exists(exePath))
            {
                exePath = Application.StartupPath + @"\proxy.exe";
            }
            if (!File.Exists(exePath))
            {
                Application.Exit();
            }
            using (RegistryKey runKey = Registry.CurrentUser.OpenSubKey(keyPath, true))
            {
                //status = runKey.GetValue("ProxyStatus", "stopped").ToString();
                mode = runKey.GetValue("ProxyMode", "0").ToString();
                runKey.Close();
            }
            SetIEProxy(this.mode);
            //StartStopProxy(this.status);
        }

        //private void startMenuItem_Click(object sender, EventArgs e)
        //{
        //    StartStopProxy("running");
        //}

        //private void stopMenuItem_Click(object sender, EventArgs e)
        //{
        //    StartStopProxy("stopped");
        //}

        private void running()
        {
            gae = new Process();
            gae.StartInfo.FileName = exePath;//@"c:\windows\system32\cmd.exe ";//
            gae.StartInfo.Arguments = "";
            gae.StartInfo.CreateNoWindow = true;
            gae.StartInfo.UseShellExecute = false;
            gae.StartInfo.RedirectStandardError = true;
            gae.ErrorDataReceived += new DataReceivedEventHandler(OnDataReceived);
            gae.Start();
            gae.BeginErrorReadLine();
            gae.WaitForExit();
            gae.CancelErrorRead();
            gae.Dispose();
            this.Invoke(new MethodInvoker(delegate()
            {
                SetIEProxy("0");
            }));
        }
        private void OnDataReceived(object Sender, DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    if (log.Items.Count > 50)
                    {
                        log.Items.Clear();
                    }
                    log.Items.Insert(0, e.Data);
                }));
            }
        }
    }
}